/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package me.panpf.sketch.sample.item;

import me.panpf.sketch.Sketch;
import me.panpf.sketch.SketchImageView;
import me.panpf.sketch.datasource.DataSource;
import me.panpf.sketch.request.ShapeSize;
import me.panpf.sketch.sample.AppConfig;
import me.panpf.sketch.sample.ResourceTable;
import me.panpf.sketch.sample.slice.ImageDetailAbility;
import me.panpf.sketch.sample.slice.NetImageUtils;
import me.panpf.sketch.sample.util.DataTransferStation;
import me.panpf.sketch.sample.util.PxUtil;
import me.panpf.sketch.sample.widget.SampleImageView;
import me.panpf.sketch.shaper.RoundRectImageShaper;
import me.panpf.sketch.uri.UriModelManager;
import me.panpf.sketch.util.SketchUtils;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.utils.Point;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.common.ImageInfo;
import ohos.media.image.common.Size;

import java.util.ArrayList;
import java.util.List;

/**
 * BaiduStaggeredImageItem
 */
public class BaiduStaggeredImageItem extends BaseItemProvider {
    private static final int ROW_COUNT = 3;
    private List<String> stringList;
    private Fraction parent;
    private Context context;
    private LayoutScatter inflater;
    private DataTransferStation.PageHelper dataTransferHelper;

    public BaiduStaggeredImageItem(Fraction parent, List<String> stringList) {
        this.stringList = stringList;
        this.parent = parent;
        this.context = parent.getComponent().getContext();
        this.inflater = LayoutScatter.getInstance(context);

        dataTransferHelper = new DataTransferStation.PageHelper(parent);
        dataTransferHelper.onCreate(null);
    }

    @Override
    public int getCount() {
        int size = stringList.size();
        int remainder = size % ROW_COUNT;
        int cnt = (size - remainder) / ROW_COUNT;
        cnt = remainder > 0 ? cnt + 1 : cnt;
        return cnt;
    }

    @Override
    public String getItem(int i1) {
        if (i1 >= stringList.size()) {
            return null;
        }
        return stringList.get(i1);
    }

    @Override
    public long getItemId(int i1) {
        return i1;
    }

    @Override
    public Component getComponent(int i1, Component convertView, ComponentContainer componentContainer) {
        Component view = convertView;
        final ViewHolder holder;
        if (convertView == null) {
            view = inflater.parse(ResourceTable.Layout_list_item_image_baidugif, componentContainer, false);
            holder = new ViewHolder();
            holder.itemImages = new ArrayList<>();
            holder.itemImages.add((SampleImageView) view.findComponentById(ResourceTable.Id_item_image_1));
            holder.itemImages.add((SampleImageView) view.findComponentById(ResourceTable.Id_item_image_2));
            holder.itemImages.add((SampleImageView) view.findComponentById(ResourceTable.Id_item_image_3));

            Point pt = new Point();
            DisplayManager.getInstance().getDefaultDisplay(context).get().getSize(pt);
            int width = (int) (((double)pt.getPointX() - (PxUtil.vp2px(4 * 4))) / 3d);
            for (int i = 0; i < ROW_COUNT; i++) {
                holder.itemImages.get(i).setComponentSize(width, width);
                holder.itemImages.get(i).setPage(SampleImageView.Page.PHOTO_LIST);
            }

            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        int rank = i1 * ROW_COUNT;
        for (int r = 0; r < ROW_COUNT; r++) {
            int pos = rank + r;
            SampleImageView itemImage = holder.itemImages.get(r);
            if (getItem(pos) == null) {
                itemImage.setVisibility(Component.INVISIBLE);
            } else {
                itemImage.setVisibility(Component.VISIBLE);
                itemImage.setTag(new ImagePosition(pos));
                setItemImageClickedListener(itemImage);
                itemImage.getOptions().setLoadingImage(ResourceTable.Media_image_loading)
                        .setErrorImage(ResourceTable.Media_image_error)
                        .setPauseDownloadImage(ResourceTable.Media_image_pause_download)
                        .setShapeSize(ShapeSize.byViewFixedSize());
                if (AppConfig.getBoolean(context, AppConfig.Key.SHOW_ROUND_RECT_IN_PHOTO_LIST)) {
                    itemImage.getOptions().setShaper(new RoundRectImageShaper(SketchUtils.dp2px(context, 6)));
                }
                itemImage.displayImage(getItem(pos));
            }
        }

        return view;
    }

    private void setItemImageClickedListener(SampleImageView itemImage) {
        itemImage.setClickedListener(component -> {
            ImagePosition tag = (ImagePosition) component.getTag();

            int clickedPos = tag.getPos();
            String finalOptionsKey = ((SketchImageView) component).getOptionsKey();
            // 含有这些信息时，说明这张图片不仅仅是缩小，而是会被改变，因此不能用作loading图了
            if (finalOptionsKey.contains("Resize")
                    || finalOptionsKey.contains("ImageProcessor")
                    || finalOptionsKey.contains("thumbnailMode")) {
                finalOptionsKey = null;
            }

            List<String> images = new ArrayList<>();
            UriModelManager manager = Sketch.with(context).getConfiguration().getUriModelManager();

            NetImageUtils.getInstance().datas.clear();
            for (int j = 0; j < stringList.size(); j++) {
                String path = stringList.get(j);
                ImageInfo imageInfo;
                try {
                    DataSource dataSource = manager.match(path).getDataSource(context, path, null);
                    ImageSource imageSource = ImageSource.create(dataSource.getInputStream(), null);
                    imageInfo = imageSource.getImageInfo();
                } catch (Exception ignored) {
                    imageInfo = new ImageInfo();
                    imageInfo.size = new Size(100, 100);
                }
                images.add(path);
                ImageDetailAbility.MImageInfo info = new ImageDetailAbility.MImageInfo(imageInfo, SketchUtils.isGifImage(path), path, null);
                NetImageUtils.getInstance().datas.put(path, info);
            }

            if (images.size() > clickedPos) {
                String urlList = dataTransferHelper.put("urlList", images);
                ImageDetailAbility.launch(parent.getFractionAbility(),
                        urlList,
                        finalOptionsKey, clickedPos);
            }
        });
    }

    private static class ViewHolder {
        private ArrayList<SampleImageView> itemImages;
    }

    private static class ImagePosition {
        private int pos;

        public ImagePosition(int pos) {
            this.pos = pos;
        }

        public int getPos() {
            return this.pos;
        }
    }
}
